package com.heima.article.service.impl;

import com.alibaba.fastjson.JSON;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.heima.article.service.ApArticleService;
import com.heima.article.mapper.ApArticleMapper;
import com.heima.article.service.ArticleFreemarkerService;
import com.heima.common.constants.ArticleConstants;
import com.heima.common.redis.RedisCacheService;
import com.heima.model.article.articleDto.ArticleDto;
import com.heima.model.article.articleDto.ArticleHomeDto;
import com.heima.model.article.contants.ArticleContants;
import com.heima.model.article.pojos.ApArticle;
import com.heima.model.article.pojos.ApArticleConfig;
import com.heima.model.article.pojos.ApArticleContent;
import com.heima.model.article.vos.HotArticleVo;
import com.heima.model.common.dtos.ResponseResult;
import com.heima.model.common.enums.AppHttpCodeEnum;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang.StringUtils;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import java.util.Date;
import java.util.List;

/**
 * @author 石头
 * @description 针对表【ap_article(文章信息表，存储已发布的文章)】的数据库操作Service实现
 * @createDate 2022-06-12 11:40:17
 */
@Service
@Slf4j
public class ApArticleServiceImpl extends ServiceImpl<ApArticleMapper, ApArticle>
        implements ApArticleService {

    @Resource
    private ApArticleMapper apArticleMapper;

    @Resource
    private ApArticleConfigServiceImpl apArticleConfigServiceImpl;

    @Resource
    private ApArticleContentServiceImpl apArticleContentServiceImpl;

    /**
     * 加载文章
     *
     * @param articleHomeDto
     * @return ResponseResult
     */
    @Override
    public ResponseResult load(ArticleHomeDto articleHomeDto, Short type) {
        Integer size = articleHomeDto.getSize();
        Date minBehotTime = articleHomeDto.getMinBehotTime();
        Date maxBehotTime = articleHomeDto.getMaxBehotTime();
        String tag = articleHomeDto.getTag();

        // 校验参数 为空将常量重新赋值
        // size 下限
        if (size == null || size <= 0) {
            articleHomeDto.setSize(10);
        }

        // size 上限
        articleHomeDto.setSize(Math.min(size, 50));

        if (minBehotTime == null) {
            articleHomeDto.setMinBehotTime(new Date());
        }
        if (maxBehotTime == null) {
            articleHomeDto.setMaxBehotTime(new Date());
        }
        // 频道
        if (StringUtils.isBlank(tag)) {
            articleHomeDto.setTag(ArticleContants.DEFAULT_TAG);
        }

        // 查询列表
        List<ApArticle> articleList = apArticleMapper.load(articleHomeDto, type);
        return ResponseResult.okResult(articleList);
    }


    @Resource
    private ArticleFreemarkerService articleFreemarkerService;

    /**
     * 保存文章
     *
     * @param articleDto
     * @return
     */
    @Override
    public ResponseResult saveArticle(ArticleDto articleDto) {
        log.info("---文章保存开始---");
        if (articleDto == null) {
            return ResponseResult.errorResult(AppHttpCodeEnum.PARAM_INVALID);
        }
        Long id = articleDto.getId();
        ApArticle article = null;
        // 新增
        if (id == null) {
            // 对象拷贝
            article = new ApArticle();
            BeanUtils.copyProperties(articleDto, article);
            this.save(article);

            // 新增文章配置
            ApArticleConfig apArticleConfig = new ApArticleConfig(article.getId());
            apArticleConfigServiceImpl.save(apArticleConfig);

            // 新增内容
            ApArticleContent apArticleContent = new ApArticleContent();
            apArticleContent.setArticleId(article.getId());
            apArticleContent.setContent(articleDto.getContent());
            apArticleContentServiceImpl.save(apArticleContent);
            log.info("article.getId():{}", article.getId());
            //异步调用 生成静态文件上传到minio中
            articleFreemarkerService.buildArticleToMinIO(article, articleDto.getContent());

            return ResponseResult.okResult(article.getId());
        }
        // 根据文章id查询文章信息是否存在
        article = apArticleMapper.selectById(id);
        if (article == null) {
            return ResponseResult.errorResult(AppHttpCodeEnum.ESSAY_NOT_EXIST);
        }
        // 存在就修改文章内容和文章信息
        // 修改文章信息
        BeanUtils.copyProperties(articleDto, article);
        this.updateById(article);
        // 修改文章内容
        ApArticleContent apArticleContent = apArticleContentServiceImpl.getOne(Wrappers.<ApArticleContent>lambdaQuery().eq(ApArticleContent::getArticleId, id));
        apArticleContent.setContent(articleDto.getContent());
        apArticleContent.setArticleId(articleDto.getId());
        apArticleContentServiceImpl.updateById(apArticleContent);
        log.info("article.getId():{}", article.getId());

        //异步调用 生成静态文件上传到minio中
        articleFreemarkerService.buildArticleToMinIO(article, articleDto.getContent());

        return ResponseResult.okResult(article.getId());
    }

    @Resource
    private RedisCacheService redisCacheService;

    /**
     * 加载文章列表
     *
     * @param dto
     * @param type      1 加载更多   2 加载最新
     * @param firstPage true  是首页  flase 非首页
     * @return
     */
    @Override
    public ResponseResult load2(ArticleHomeDto dto, Short type, boolean firstPage) {
        if (firstPage) {
            String jsonStr = redisCacheService.get(ArticleConstants.HOT_ARTICLE_FIRST_PAGE + dto.getTag());
            if (StringUtils.isNotBlank(jsonStr)) {
                List<HotArticleVo> hotArticleVoList = JSON.parseArray(jsonStr, HotArticleVo.class);
                ResponseResult responseResult = ResponseResult.okResult(hotArticleVoList);
                return responseResult;
            }
        }
        return load(dto, type);
    }
}



